/**
 *    Copyright 2009-2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.JdbcType;

/**
 * @author Clinton Begin
 */

/**
 * XMLConfigBuilder  以及解析 Mapper XMLMapperBuilder 都继承于 BaseBuilder
 *
 * 它们对于 XML 文件本身技术上的加载和解析都委托给了 XPathParser 最终用的是 JDK 自带的 xml 解析器，并非第三方的 dom4j。
 * 底层使用了 XPath 方式进行节点解析。
 */
public class XMLConfigBuilder extends BaseBuilder {

  private boolean parsed;
  private XPathParser parser;
  private String environment;
  // 是 mybatis  提供默认反射工厂实现
  private ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

  public XMLConfigBuilder(Reader reader) {
    this(reader, null, null);
  }

  public XMLConfigBuilder(Reader reader, String environment) {
    this(reader, environment, null);
  }

  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
    //   reader : 字符流  、 validation:是否进行 DTD校验  、 props : 属性配置  、XMLMapperEntityResolver : XML实体解析器
    this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  public XMLConfigBuilder(InputStream inputStream) {
    this(inputStream, null, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment) {
    this(inputStream, environment, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
    this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
    // 调用父类构造器 （主要是设置类型别名注册器，以及类型处理器注册器）
    super(new Configuration());
    ErrorContext.instance().resource("SQL Mapper Configuration");
    this.configuration.setVariables(props);
    this.parsed = false;
    this.environment = environment;
    this.parser = parser;
  }

  /**
   * 真正 Configuration 构建逻辑就在 XMLConfigBuilder.parse() 这里
   * @return
   */
  public Configuration parse() {
    // 如果解析过了
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }

    parsed = true;
    // MyBatis 配置文件解析 主流程
    // parser.evalNode("/configuration") 返回一个 XNode 节点
    // 读取 configuration 节点下的内容
    // XNode 里面主要把关键的节点属性和占位符变量结构化出来，
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

  /**
   *  解析 MyBatis 配置文件的主流程
   * @param root
   */
  private void parseConfiguration(XNode root) {
    /**
     *
     */
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));
      /**
       * 我们在使用 MyBatis 执行查询语句的时候，通常都会有一个返回类型，这个是在 Mapper文件中给 sql增加一个resultType或 resultMap来控制。
       * 只要定义了这个配置就能自动返回我们想要的结果。
       * 在JDBC中查询 的结果会保存在一个结果集中，其实MyBatis 也是这个原理，只不过MyBatis在创建结果集的时候，
       * 会使用定义的 对象工厂 DefaultObjectFactory来完成对应的工作。
       *
       */
      objectFactoryElement(root.evalNode("objectFactory"));
      // 对象包装器
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));

      /**
       *  反射工厂
       *  mybatis 支持用户自定义反射工厂，用的不多，要实现反射工厂，只要实现 ReflectorFactory接口，
       *  默认的反射工厂是 DefaultReflectorFactory  一般用默认的就可以
       */
      reflectionFactoryElement(root.evalNode("reflectionFactory"));
      settingsElement(root.evalNode("settings"));
      // read it after objectFactory and objectWrapperFactory issue #631
      // 加载环境配置
      environmentsElement(root.evalNode("environments"));
      // 支持多数据库厂商
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      // 加载类型处理器
      typeHandlerElement(root.evalNode("typeHandlers"));
      // 加载 mapper 文件的  初始化 MappedStatement 对象
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

  /**
   * 解析类型别名
   * @param parent
   */
  private void typeAliasesElement(XNode parent) {
    /**
     * 1. 当这样配置之后、 Blog1 可以用在任何 使用了 domain.blog.Blog1 中
     * <typeAliases>
     *   <typeAlias alias="Blog1" type="domain.blog.Blog1"/>
     *   <typeAlias alias="Blog2" type="domain.blog.Blog2"/>
     * </typeAliases>
     *
     * 2. 配置了 package 之后，Mybatis 会在包名下面搜索需要的 Java Bean
     *  blog 包下的 JavaBean 在没有注解的情况下 会使用 Bean的首字母小写的非限定类名来作为它的别名
     *  如 domain.blog.Student 的别名是 student
     * <typeAliases>
     *   <package name="domain.blog"/>
     * </typeAliases>
     */
    if (parent != null) {
      // 所有子节点
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String typeAliasPackage = child.getStringAttribute("name");
          // configuration 注册别名
          configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
        } else {
          String alias = child.getStringAttribute("alias");   // 别名
          String type = child.getStringAttribute("type");     // 全限定类名
          try {
            // 通过反射找到这个 JavaBean
            Class<?> clazz = Resources.classForName(type);
            if (alias == null) {  // 别名为空
              //类型别名注册器
              typeAliasRegistry.registerAlias(clazz);
            } else {
              typeAliasRegistry.registerAlias(alias, clazz);
            }
          } catch (ClassNotFoundException e) {
            throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
          }
        }
      }
    }
  }

  /**
   * 加载插件 几乎所有优秀的框架都会预留插件体系以便扩展
   * 最常用的插件应该是分页插件了  PageHelper
   * 再比如 druid 连接池提供的各种监控、拦截、预发检查功能。
   * @param parent
   * @throws Exception
   */
  private void pluginElement(XNode parent) throws Exception {
    /**
     * <plugins>
     * 		<plugin interceptor="">
     * 			<property name="" value=""/>
     * 		</plugin>
     * 		<plugin interceptor=""></plugin>
     * 	</plugins>
     */
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        // 插件在具体使用的时候，采用的是拦截器的模式，要注册为 mybatis 的插件、
        // 必须实现 org.apache.ibatis.plugin.interceptor 接口，每个插件可以有自己的属性
        //interceptor属性值既可以完整的类名，也可以是别名，只要别名在typealias中存在即可，如果启动时无法解析，会抛出ClassNotFound异常。
        String interceptor = child.getStringAttribute("interceptor");
        Properties properties = child.getChildrenAsProperties();
        // 创建拦截器实例
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
        interceptorInstance.setProperties(properties);
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }

  private void objectFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties properties = context.getChildrenAsProperties();
      ObjectFactory factory = (ObjectFactory) resolveClass(type).newInstance();
      factory.setProperties(properties);
      configuration.setObjectFactory(factory);
    }
  }

  /**
   * 创建对象包装器工厂
   * 主要用来包装返回 result对象，比如可以用来设置某些敏感字段脱敏或者加密等，
   * 默认对象包装器工厂是 DefaultObjectWrapperFactory
   * @param context
   * @throws Exception
   */
  private void objectWrapperFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).newInstance();
      configuration.setObjectWrapperFactory(factory);
    }
  }

  private void reflectionFactoryElement(XNode context) throws Exception {
    if (context != null) {
       String type = context.getStringAttribute("type");
       ReflectorFactory factory = (ReflectorFactory) resolveClass(type).newInstance();
       configuration.setReflectorFactory(factory);
    }
  }

  /**
   * 解析 Properties 的方法
   * @param context
   * @throws Exception
   */
  private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      // 加载 properties 节点为 Properties 对象
      // 将 properties 里 property 里 name(key) value(value) 封装成对象 Properties
      Properties defaults = context.getChildrenAsProperties();
      // <properties  resouce = "db.properties">  将 数据库的一些信息放在 db.properties 配置文件中
      String resource = context.getStringAttribute("resource");
      // <properties  url = "">
      String url = context.getStringAttribute("url");
      // resource 和 url 不能同时存在
      if (resource != null && url != null) {
        throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
      }
      if (resource != null) {
        // db.properties -> Properties
        defaults.putAll(Resources.getResourceAsProperties(resource));
      } else if (url != null) {
        defaults.putAll(Resources.getUrlAsProperties(url));
      }
      // Configuration 配置类中 拿 Properties对象
      Properties vars = configuration.getVariables();
      if (vars != null) {
        // Properties 继承 HashTable  putAll() 将里面的 key value  添加到 defaults 中
        defaults.putAll(vars);
      }
      parser.setVariables(defaults);
      configuration.setVariables(defaults);
    }
  }


  /**
   * 设置 标签 、配置 MyBatis 运行时的一些行为 ：缓存、延时加载、结果集控制、执行器、分页设置、命名规则
   * @param context
   * @throws Exception
   */
  private void settingsElement(XNode context) throws Exception {
    if (context != null) {
      Properties props = context.getChildrenAsProperties();
      // Check that all settings are known to the configuration class
      // 检查所有属性，确保他们在 Configuration 中已定义        localReflectoryFacrtory 是 mybatis  提供默认反射工厂实现
      MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
      for (Object key : props.keySet()) {
        if (!metaConfig.hasSetter(String.valueOf(key))) {
          throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
        }
      }
      // configuration 设置 属性
      configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
      configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
      configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
      configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
      configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), true));
      configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
      configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
      configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
      configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
      configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
      configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
      configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
      configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
      configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
      configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
      configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
      configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
      configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
      configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
      configuration.setLogPrefix(props.getProperty("logPrefix"));
      configuration.setLogImpl(resolveClass(props.getProperty("logImpl")));
      configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
    }
  }

  /**
   * 加载环境配置
   * 可以说是 MyBatis-Config 中最重要的部分，允许给开发、生产环境配置不同的 environment
   * 根据不同的环境加载不同的配置，
   * 如果在SqlSessionFactoryBuilder调用期间没有传递使用哪个环境的话，默认会使用一个名为default”的环境。
   * 找到对应的environment之后，就可以加载事务管理器和数据源了。
   * 事务管理器和数据源类型这里都用到了类型别名，JDBC/POOLED都是在mybatis内置提供的，
   * 在Configuration构造器执行期间注册到TypeAliasRegister。
   *
   * mybatis内置提供JDBC和MANAGED两种事务管理方式，
   * 前者主要用于简单JDBC模式，
   * 后者主要用于容器管理事务，一般使用JDBC事务管理方式。
   * mybatis内置提供JNDI、POOLED、UNPOOLED三种数据源工厂，一般情况下使用POOLED数据源。
   * @param context    root.evalNode("environments")
   * @throws Exception
   */
  private void environmentsElement(XNode context) throws Exception {
    /**
     * <environments default="development">
     * 		<environment id="development">
     * 			<transactionManager type="JDBC"/>
     * 			<dataSource type="POOLED">
     * 				<property name="driver" value="com.mysql.custom.jdbc.Driver"/>
     * 				<property name="url" value="custom.jdbc:mysql://localhost:3306/lfBase?useUnicode=true"/>
     * 				<property name="username" value="root"/>
     * 				<property name="password" value="root" />
     * 			</dataSource>
     * 		</environment>
     * 	</environments>
     */
    if (context != null) {
      if (environment == null) {
        // 如果当前没有环境，会给一个名为 属性为 default 的环境  default="development"
        environment = context.getStringAttribute("default");
      }
      for (XNode child : context.getChildren()) {
        String id = child.getStringAttribute("id");
        // id = "development"  需要和 当前 environment 环境名 一样
        if (isSpecifiedEnvironment(id)) {
          // 事务配置，并创建事务工厂
          TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
          // 数据源配置，并且实例化数据源，数据源是必须的
          DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
          DataSource dataSource = dsFactory.getDataSource();
          //创建 Environment.Builder
          /**
           * 环境名称 + 事务工厂 + 数据源
           */
          Environment.Builder environmentBuilder = new Environment.Builder(id)
              .transactionFactory(txFactory)
              .dataSource(dataSource);
          configuration.setEnvironment(environmentBuilder.build());
        }
      }
    }
  }

  private void databaseIdProviderElement(XNode context) throws Exception {
    DatabaseIdProvider databaseIdProvider = null;
    if (context != null) {
      String type = context.getStringAttribute("type");
      // awful patch to keep backward compatibility
      if ("VENDOR".equals(type)) {
          type = "DB_VENDOR";
      }
      Properties properties = context.getChildrenAsProperties();
      databaseIdProvider = (DatabaseIdProvider) resolveClass(type).newInstance();
      databaseIdProvider.setProperties(properties);
    }
    Environment environment = configuration.getEnvironment();
    if (environment != null && databaseIdProvider != null) {
      String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
      configuration.setDatabaseId(databaseId);
    }
  }

  /**
   * 环境中 事务
   * @param context       evalNode("transactionManager")
   * @return
   * @throws Exception
   */
  private TransactionFactory transactionManagerElement(XNode context) throws Exception {
    /**
     * <transactionManager type="JDBC"/>
     */
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a TransactionFactory.");
  }

  /**
   * 数据源工厂创建
   * @param context
   * @return
   * @throws Exception
   */
  private DataSourceFactory dataSourceElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      DataSourceFactory factory = (DataSourceFactory) resolveClass(type).newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a DataSourceFactory.");
  }

  /**
   *  类型处理器
   * @param parent      evalNode("typeHandlers")
   * @throws Exception
   */
  private void typeHandlerElement(XNode parent) throws Exception {
    /**
     * <typeHandlers>
     *     <!--<package name="gov.huang"/>-->
     * 		<typeHandler handler="" />              handler 属性直接直接配置我们制定的 TypeHandler
     * 		<typeHandler javaType="" handler="" />  例如配置 String
     * 		<typeHandler jdbcType="" handler="" />  例如配置 varchar
     * 	</typeHandlers>
     */
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        // package 和 typeHandler 不能一起配置
        if ("package".equals(child.getName())) {
          //当配置 package 的时候， mybatis 会去配置的 package 扫描 TypeHandler
          String typeHandlerPackage = child.getStringAttribute("name");
          typeHandlerRegistry.register(typeHandlerPackage);
        } else {
          String javaTypeName = child.getStringAttribute("javaType");
          String jdbcTypeName = child.getStringAttribute("jdbcType");
          // handler 就是我们配置的 typeHandler
          String handlerTypeName = child.getStringAttribute("handler");
          Class<?> javaTypeClass = resolveClass(javaTypeName);
          JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
          Class<?> typeHandlerClass = resolveClass(handlerTypeName);
          if (javaTypeClass != null) {
            if (jdbcType == null) {
              typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
            } else {
              typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
            }
          } else {
            typeHandlerRegistry.register(typeHandlerClass);
          }
        }
      }
    }
  }

  /**
   *  加载 mapper 文件
   *  mapper 文件是MyBatis 框架的核心之处 、所有的用户的 sql 语句都编写在 Mapper 文件中，
   * @param parent      root.evalNode("mappers")
   * @throws Exception
   */
  private void mapperElement(XNode parent) throws Exception {
    /**
     * <mappers>
     * 	    <package name=""/>
     * 	    //<mapper resource="gov/huang/mapper/UserMapper.xml"/>
     * 		//<mapper class=""></mapper>
     * 		//<mapper url=""></mapper>
     * 	</mappers>
     *
     * 	MyBatis 提供了两类 配置 mapper 的方法，第一类使用 Package自动搜索的模式
     * 	    这样指定 package 包下所有的接口都会被注册为 mapper
     * 	    <mappers>
     *          <package name="org.mybatis.builder"/>
     *      </mappers>
     *
     *  另一类是明确 mapper 可通过 resource  url  class  进行细分
     *
     *  <mappers>
     *   <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
     *   <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
     *   <mapper resource="org/mybatis/builder/PostMapper.xml"/>
     * </mappers>
     * <mappers>
     *   <mapper url="file:///var/mappers/AuthorMapper.xml"/>
     *   <mapper url="file:///var/mappers/BlogMapper.xml"/>
     *   <mapper url="file:///var/mappers/PostMapper.xml"/>
     * </mappers>
     * <mappers>
     *   <mapper class="org.mybatis.builder.AuthorMapper"/>
     *   <mapper class="org.mybatis.builder.BlogMapper"/>
     *   <mapper class="org.mybatis.builder.PostMapper"/>
     * </mappers>
     */
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        // 这样指定 ，package 下的所有接口都会被注册为 mapper
        if ("package".equals(child.getName())) {
          String mapperPackage = child.getStringAttribute("name");
          // 例： package = gov.huang.mapper
          configuration.addMappers(mapperPackage);
        } else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();       // 解析xml文件流
          } else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            InputStream inputStream = Resources.getUrlAsStream(url);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();      // 解析xml文件流
          } else if (resource == null && url == null && mapperClass != null) {
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }

  private boolean isSpecifiedEnvironment(String id) {
    if (environment == null) {
      throw new BuilderException("No environment specified.");
    } else if (id == null) {
      throw new BuilderException("Environment requires an id attribute.");
    } else if (environment.equals(id)) {
      return true;
    }
    return false;
  }

}
